package com.lcredu.json;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author 黎长容
 * @date 2025-07-02 20:15
 */
public class json {
    static Gson gson = new Gson();

    public static void main(String[] args) {


        Book book1 = new Book(100, "百草园");
        Book book2 = new Book(2, "三味书屋");
        ArrayList<Book> books = new ArrayList<>();
        books.add(book1);
        books.add(book2);

        print();
        //bean->json
        String bookJson = getJson(book1);
        System.out.println(bookJson);

        //json->bean
        System.out.println(fromJson(bookJson, Book.class));
        print();

        //arrayList->json
        String bookListJson = getJson(books);
        System.out.println(bookListJson);

        // json->arraylist
        //解释
        //1. 加了大括号表示他是一个匿名内部类(子类)
        //2. 这样做表示它调用自己的无参构造器的时候就会自动的调用super关键字
        //3. 就能调用到父类中受保护的无参构造器了
        /**
         *  protected TypeToken() {
         *         this.type = getSuperclassTypeParameter(this.getClass());
         *         this.rawType = Types.getRawType(this.type);
         *         this.hashCode = this.type.hashCode();
         *     }
         */
        Type type = new TypeToken<List<Book>>() {
        }.getType();

//        System.out.println(type.getClass());

        //java.util.List<com.lcredu.json.Book>
//        System.out.println(type);
        List<Book> bookList2 = gson.fromJson(bookListJson, type);
        System.out.println(bookList2);
        print();

        //map->string
        HashMap<String, Book> stringBookHashMap = new HashMap<>();
        stringBookHashMap.put("k1", book1);
        stringBookHashMap.put("k2", book2);
        String stringMapJson = getJson(stringBookHashMap);
        System.out.println("stringMapJson=" + stringMapJson);

        //string->map
        Map hashMap = gson.fromJson(stringMapJson, new TypeToken<HashMap<String, Book>>() {
        }.getType());


        System.out.println(hashMap);

    }

    private static void print() {
        System.out.println("============");
    }

    private static <T> String getJson(T t) {
        return gson.toJson(t);
    }

    private static <T> T fromJson(String jsonString, Class<T> clazz) {
        return gson.fromJson(jsonString, clazz);
    }

}
